import type {
  RouteLocationNormalizedGeneric,
  RouteLocationNormalizedLoadedGeneric,
  RouteRecordName
} from "vue-router"

export const useTagsViewStore = defineStore(
  "tagsView",
  () => {
    const visitedViews = ref<RouteLocationNormalizedLoadedGeneric[]>([])

    const addView = (view: RouteLocationNormalizedLoadedGeneric) => {
      addCacheView(view)
      const isEixst = visitedViews.value.some((v) => v.path === view.path)
      if (isEixst) return

      const newViews = {
        ...view,
        title: view.meta?.title
      }
      visitedViews.value.push(newViews)
    }

    const delView = (view: RouteLocationNormalizedLoadedGeneric) => {
      const existIndex = visitedViews.value.findIndex(
        (v) => v.path === view.path
      )
      if (existIndex > -1) {
        visitedViews.value.splice(existIndex, 1)
      }

      delCacheView(view)
    }

    const cacheViews = ref<RouteRecordName[]>([])

    const addCacheView = (view: RouteLocationNormalizedGeneric) => {
      if (cacheViews.value.includes(view.name)) return
      if (!view.meta.noCache) {
        cacheViews.value.push(view.name)
      }

      console.log("cacheViews", cacheViews.value)
    }

    const delCacheView = (view: RouteLocationNormalizedGeneric) => {
      const index = cacheViews.value.indexOf(view.name)
      if (index > -1) {
        cacheViews.value.splice(index, 1)
      }
    }

    const delAllViews = () => {
      visitedViews.value = visitedViews.value.filter((item) => item.meta?.affix)
      console.log("delAllViews visitedViews", visitedViews.value)
      cacheViews.value = []
    }

    const delOtherViews = (view: RouteLocationNormalizedGeneric) => {
      visitedViews.value = visitedViews.value.filter(
        (item) => item.meta.affix || item.path === view.path
      )

      cacheViews.value = cacheViews.value.filter((item) => item === view.name)
    }

    const delCurrentView = (view: RouteLocationNormalizedGeneric) => {
      visitedViews.value = visitedViews.value.filter(
        (item) => item.meta.affix || item.path !== view.path
      )

      cacheViews.value = cacheViews.value.filter((item) => item !== view.name)
    }

    return {
      visitedViews,
      addView,
      delView,
      delAllViews,
      delOtherViews,
      delCurrentView,
      cacheViews,
      addCacheView,
      delCacheView
    }
  },
  {
    persist: {
      storage: window.localStorage, // 指定持久化方式
      pick: ["visitedViews", "cacheViews"] // 指定要持久化的数据
    }
  }
)
